use time::{format_description, UtcOffset};
use tracing::level_filters::LevelFilter;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{fmt, layer::SubscriberExt};

use super::config::global_config;

/**
 * 根据配置文件进行日志的配置。
 */
pub fn init_tracing_log() -> WorkerGuard {
	let time_format =
		format_description::parse("[hour repr:24]:[minute]:[second].[subsecond digits:6]").expect("parse  time_format time format");
	let offset_time = UtcOffset::from_hms(8, 0, 0).expect("无法得到时间偏移");

	let file_appender = tracing_appender::rolling::daily(
		global_config().log_path.unwrap_or("./logs/"),
		global_config().log_file_name.unwrap_or("trace.log"),
	);
	let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);

	//这个是发布对象。
	let subscriber = tracing_subscriber::registry();
	let level = match global_config().log_level.unwrap_or("TRACE") {
		"OFF" => LevelFilter::OFF,
		"ERROR" => LevelFilter::ERROR,
		"WARN" => LevelFilter::WARN,
		"INFO" => LevelFilter::INFO,
		"DEBUG" => LevelFilter::DEBUG,
		_ => LevelFilter::TRACE,
	};
	let subscriber = subscriber.with(level);
	//可以使用with向多个部分进行发布数据。
	if global_config().log_to_console.unwrap_or(true) {
		let subscriber = subscriber.with(Some(
			fmt::Layer::new()
				.with_target(false) //不显示最外层块
				.with_line_number(true)
				.with_timer(fmt::time::OffsetTime::new(offset_time, time_format.clone()))
				.with_file(true),
		));

		if global_config().log_to_file.unwrap_or(true) {
			let subscriber = subscriber.with(Some(
				fmt::Layer::new()
				
					.with_ansi(false) //去掉颜色显示
					.with_target(false) //不显示最外层块
					.with_line_number(true)
					.with_file(true)
					.with_timer(fmt::time::OffsetTime::new(offset_time, time_format))
					.with_writer(non_blocking),
			));

			tracing::subscriber::set_global_default(subscriber).expect("日志组件初始化失败");
		} else {
			tracing::subscriber::set_global_default(subscriber).expect("日志组件初始化失败");
		}
	} else if global_config().log_to_file.unwrap_or(true) {
		let subscriber = subscriber.with(Some(
			fmt::Layer::new()
				.with_ansi(false) //去掉颜色显示
				.with_target(false) //不显示最外层块
				.with_line_number(true)
				.with_file(true)
				.with_timer(fmt::time::OffsetTime::new(offset_time, time_format))
				.with_writer(non_blocking),
		));
		tracing::subscriber::set_global_default(subscriber).expect("日志组件初始化失败");
	} else {
		tracing::subscriber::set_global_default(subscriber).expect("日志组件初始化失败");
	}

	guard
}

